<template>
  <div class="page">
    <!-- 条件筛选 -->
    <div class="page_filter">
      <el-input v-model="form.sn" clearable placeholder="请输入摄像机SN码" @clear="form.page=1;queryList()"></el-input>
      <el-select v-model.trim="form.authStatus" clearable placeholder="授权状态" @clear="form.page=1;queryList()">
        <el-option v-for="item in authStatusList" :key="item.code" :label="item.name" :value="item.code">
        </el-option>
      </el-select>
      <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
    </div>
    <div class="page_main">
      <el-button icon="el-icon-plus" @click.stop="handleAdd" class="common_btn-small">添加摄像机</el-button>
      <el-button icon="el-icon-s-promotion" slot="reference" class="common_btn-small" @click="showAuth">设备授权
      </el-button>
      <!-- table -->
      <div class="common_btnBox">
        <i class="iconfont iconzongshu icon-size"></i>
        总数：{{form.total}}
      </div>
      <el-table :data="tableList" border @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" :selectable="selected" :header-cell-class-name="cellClass"
                         width="55"></el-table-column>
        <el-table-column prop="sn" min-width="150" label="摄像机SN码" align="center"></el-table-column>
        <el-table-column prop="cameraPhone" width="120" label="物联网卡" align="center"></el-table-column>
        <el-table-column prop="authDeptTreeId" width="120" label="授权状态" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.authDeptTreeId" effect="dark" size="small">已授权</el-tag>
            <el-tag v-else size="small" effect="dark" type="info">未授权</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="battery" width="100" label="电压"></el-table-column>
        <el-table-column prop="asignal" width="100" label="信号">
        </el-table-column>
        <el-table-column prop="bizTime" width="165" label="拍照时间">
          <template slot-scope="scope">{{scope.row.bizTime | formatTimer}}</template>
        </el-table-column>
        <el-table-column prop="bizTime" width="165" label="上传时间">
          <template slot-scope="scope">{{scope.row.bizCreateTime | formatTimer}}</template>
        </el-table-column>
        <el-table-column prop="updateTime" label="操作时间" width="165" align="center">
          <template slot-scope="scope">{{scope.row.updateTime | formatTimer}}</template>
        </el-table-column>
        <el-table-column prop="operator" label="操作人" width="160" align="center"></el-table-column>
        <el-table-column v-if="firstData.type!=2" label="操作" width="220" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑
            </el-button>
            <button class="btn_prohibit" @click="goTest(scope.row.sn)">调试操作</button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="form.page"
        :page-size="form.pageSize"
           :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
              layout="sizes, prev, pager, next"
        :total="form.total">
      </el-pagination>
      <!-- 分页器 -->
    </div>
    <!-- 新增授权 -->
    <el-dialog title="选择授权的客户" :visible.sync="isShowDialog" :close-on-click-modal="false" width="520px">
      <!-- 具体form表单 -->
      <el-cascader style="width: 100%" :options="monitorUnitTree" ref="cascader" clearable v-model="selectedFromOptions"
                   change-on-select
                   placeholder="请选择授权单位" @change="selectFromUnit"></el-cascader>
      <!-- 操作按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="info" class="common_btn-white" @click="isShowDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="submitAuth">确定</el-button>
      </span>
    </el-dialog>
    <el-drawer
      :modal="false"
      :title="info.title"
      :close-on-click-modal="false"
      size="50%"
      :visible.sync="info.dialogVisible">
      <div class="demo-drawer__content" style="padding: 20px">
        <el-form  inline label-position="left" ref="form" :rules="rules" label-width="100px" :model="currentRow">
          <el-form-item label="摄像机SN码" prop="sn">
            <el-input v-model="currentRow.sn" placeholder="请输入非汉字" clearable
                      class="dialog-input" onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"></el-input>
          </el-form-item>

          <el-form-item label="物联卡号" prop="cameraPhone">
            <el-input v-model="currentRow.cameraPhone" placeholder="物联卡号" clearable
                      class="dialog-input"></el-input>
          </el-form-item>
          <el-form-item label="摄像机厂家" prop="cameraManufactor">
            <el-select v-model.trim="currentRow.cameraManufactor" clearable placeholder="选择摄像机厂家">
              <el-option v-for="item in EnumCameraManufactorList" :key="item.code" :label="item.name"
                         :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-divider content-position="left"><span style="font-size: 20px;color: #1990FE">摄像机拍摄任务</span></el-divider>
        <div class="addTable">
          <el-button icon="el-icon-plus" type="success" style="margin:20px 0" @click="addRow">添加任务</el-button>
          <el-table border :data="currentRow.configList">
            <el-table-column prop="action" label="动作类型" width="110">
              <template slot-scope="scope">
                <el-select v-model="scope.row.action"
                           clearable
                           placeholder="请选择动作类型" style="width: 80px">
                  <el-option
                    v-for="item in genderList"
                    :key="item.code" :label="item.name" :value="item.code">
                  </el-option>
                </el-select>
              </template>

            </el-table-column>
            <el-table-column label="数量" prop="count">
              <template slot-scope="scope">
                <el-input v-if="scope.row.action === 1" v-model="scope.row.count" style="width:120px"
                          clearable placeholder="输入视频拍摄描述">
                  <template slot="append">秒</template>
                </el-input>
                <el-input v-else v-model="scope.row.count" style="width: 120px"
                          clearable placeholder="">
                  <template slot="append">张</template>
                </el-input>
              </template>
            </el-table-column>

            <el-table-column label="拍摄间隔" prop="frequency">
              <template slot-scope="scope">
                <el-input v-model="scope.row.frequency" style="width:120px"
                          clearable v-if="scope.row.action === 1" disabled>
                  <template slot="append">秒</template>

                </el-input>
                <el-input v-model="scope.row.frequency" style="width: 120px"
                          clearable v-else>
                  <template slot="append">秒</template>

                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="宽度" prop="width" width="160">
              <template slot-scope="scope">
                <el-input v-model="scope.row.width" style="width: 150px"
                          clearable placeholder="">
                  <template slot="append">px</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="高度" prop="height" width="160">
              <template slot-scope="scope">
                <el-input v-model="scope.row.height" style="width:150px"
                          clearable placeholder="">
                  <template slot="append">px</template>
                </el-input>
              </template>
            </el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text" style="color: red"
                  @click="deleteRow( scope.$index,scope.row,)"
                >删除
                </el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  @click="copyRow( scope.$index,scope.row)"
                >复制
                </el-button
                >
              </template>

            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="demo-drawer__footer">
        <el-button @click="info.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="validateForm" style="background: #1990FE">提交</el-button>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {getCameraList, addCamera, updateCamera, addAuthorization} from '@/services/model/equip'
import Enums from '@/utils/enums'
import Format from '@/utils/format'
import {getOrganizationTree} from "@/services/model/user";

const RULES = {
  sn: {
    required: true,
    message: '请输入摄像机标识',
    trigger: 'change'
  },
  status: {
    required: true,
    message: '请选择摄像机状态',
    trigger: 'change'
  },
}
export default {
  mixins:[Enums],
  data() {
    return {
      selectedFromOptions: [],
      monitorUnitTree: [],
      multipleSelection: [],
      genderList: [{name: "照片", code: 0}, {name: "视频", code: 1}],
      authStatusList: [{name: "未授权", code: 0}, {name: "已授权", code: 1}],
      getCameraIdOptions: [],
      info: {
        title: '',
        dialogVisible: false,
      },
      authForm: {},
      form: {
        page: 1,
        pageSize: 10
      },
      isShowDialog: false,
      rules: RULES, // 表单校验的规则
      tableList: [],
      currentRow: {
        configList: []
      }, // 新增数据
      EnumCameraManufactorList: [],
      EnumRelationStatusList: [],
      EnumDeviceStatusList: []
    }
  },
  computed: {
    firstData() {
      return this.$store.state.userInfo
    },
  },
  methods: {
    goTest(sn) {
      this.$router.push({name: 'camera', params: {sn: sn}})
    },
    selectFromUnit() {
      this.$refs.cascader.dropDownVisible = false
    },
    async getMonitorUnit() {
      let res = await getOrganizationTree({unitType: 4})
      this.monitorUnitTree = res.data || []
    },
    selected(row) {
      if (row.authDeptTreeId) {
        return false
      }
      return true
    },
    // 隐藏表头选择框
    cellClass(row) {
      if (row.columnIndex === 0) {
        return 'DisabledSelection'
      }
    },
    // 选择设备
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    async submitAuth() {
      this.authForm.authDeptTreeId = this.selectedFromOptions.join('-')
      let res = await addAuthorization(this.authForm)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: '授权成功'
        })
        this.isShowDialog= false
        this.queryList()
      }
    },
    showAuth() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'info',
          message: '先勾选授权摄像机！'
        });
        return
      }
      this.authForm = {}
      let idList = []
      this.multipleSelection.map(x => {
        idList.push(x.id)
      })
      this.authForm.idList = idList
      this.isShowDialog = true
    },
    //删除行
    deleteRow(index) {//删除改行
      this.currentRow.configList.splice(index, 1)
    },
    //复制行
    copyRow(index, row) {
      this.currentRow.configList.push({
        action: row.action,
        count: row.count,
        width: row.width,
        height: row.height,
        frequency: row.frequency,
      })
    },
    //新增表单
    addRow() {
      this.currentRow.configList.push({
        action: 0,
        count: 1,
        width: 1920,
        height: 1080,
        frequency: 5,
      })
    },
    /**
     * row  当前操作行的对象
     */
    handleEdit(row) {
      this.currentRow = JSON.parse(JSON.stringify(row))
      this.info.title = '编辑摄像机'
      this.info.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 表单提交
    validateForm() {
      if (this.currentRow.configList.length === 0) {
        this.$notify({
          type: 'error',
          title: '警告',
          message: '至少有一条摄像机设置'
        })
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.submitData()
          }
        })
      }
    },
    // 新增编辑提交数据
    async submitData() {
      // 根据ID判断使用新增还是编辑
      let action = this.currentRow.id ? updateCamera : addCamera
      let res = await action(this.currentRow)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: this.currentRow.id ? '修改成功' : '添加成功'
        })
        this.info.dialogVisible = false
        this.queryList()
        return true
      }
    },
    handleAdd() {
      this.currentRow = {
        cameraManufactor:1,
        status: 0,
        configList: [
          {
            action: 0,
            count: 1,
            width: 1920,
            height: 1080,
            frequency: 5,
          }
        ]
      }
      this.info.title = '新增摄像机'
      this.info.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.form.pageSize = val
      this.queryList()
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.form.page = val
      this.queryList()
    },
    // 查询数据
    async queryList() {
      // 由于在前端进行过滤，所以name不能传到后端
      let res = await getCameraList(this.form)
      this.tableList = res.data?.records || []
      this.form.page = Number(res.data?.current)
      this.form.total = Number(res.data?.total)
    },
  },
  mounted() {
    this.queryList()
    this.getMonitorUnit()
    //	传感器类型下拉框
    this.queryDictList(['EnumCameraManufactor','EnumRelationStatus'], ['EnumCameraManufactorList', 'EnumRelationStatusList'])
  },
  activated() {
  },
  filters: {
    // 时间格式化
    formatTimer(timer) {
      if (!timer) {
        return ''
      }
      return Format(new Date(timer), "yyyy-MM-dd hh:mm:ss")
    },
  },
}
</script>

<style lang="less" scoped>
  .el-button--text {
    color: #4caf50;
  }

  .addTable {
    overflow-y: auto;
    overflow-x: hidden;
    height: 60%;

    /deep/ .el-input-group__append {
      padding: 0;
    }
  }
</style>

